package com.hm.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.hm.reggie.common.CustomException;
import com.hm.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否完成登录
 */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static  final AntPathMatcher apm = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取本次请求的url
        String url = request.getRequestURI();
        log.info("==本次拦截到的请求是:{}",url);

        //2、判断本次请求是否需要处理（检查登录状态）
        //定义不需要处理的地址
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/backend/page/demo/*",
                "/user/sendMsg/*",
                "/user/login",
                "/favicon.ico"
        };
        boolean check = check(urls, url);

        //3、判断是否需要拦截，不需要拦截的话直接结束
        if (check){
            filterChain.doFilter(request,response);
            log.info("==无需拦截,拦截结束。");
            return;
        }

        //4-1、拦截到的请求去比对登录状态
        log.info("==后端比对登录状态");
        if (request.getSession().getAttribute("employee")!=null){
            log.info("==用户{}登录状态正常，结束拦截。",request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }

        //4-1、拦截到的请求去比对登录状态
        log.info("==前端比对登录状态");
        if (request.getSession().getAttribute("user")!=null){
            log.info("==用户{}登录状态正常，结束拦截。",request.getSession().getAttribute("user"));
            //CustomException.set
            filterChain.doFilter(request,response);
            return;
        }

        //5、到这里说明没有登录，跳转到登录页面
        log.info("==用户未登录，跳转到登录页面。  ");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


        return;

    }

    public boolean check(String[] urls,String requestUrl){
        for (String url:urls){
            boolean match = apm.match(url, requestUrl);
            if (match){
                return true;
            }
        }
        return false;
    }
}
